<?php


class UnitTable extends Doctrine_Table
{
    
    public static function getInstance()
    {
        return Doctrine_Core::getTable('Unit');
    }

    /**
     * Check whether exists a record with field values defined in $params.
     * @param array $params an array of array[fieldname] = fieldvalue
     * @return Doctrine_Record. False if no result.
     */
    public function exists(array $params = array())
    {
        return $this->findOneByValues($params);
    }

    /**
     * Find a record that has field values defined in $params.
     * @param array $params
     * @return Doctrine_Record
     */
    public function findOneByValues(array $params)
    {
        $q = $this->createQuery('dctrn_find');

        foreach ($params as $fieldName => $value)
        {
            $q->andWhere($this->buildFindByWhere($fieldName), (array) $value);
        }

        return $q->limit(1)->fetchOne(array());

    }

    /**
     * Extend from function findByDql but with limit parameter
     * @param string                    $dql Dql where clause
     * @param array $params             statement parameters
     * @param int $limit                limit
     * @param <type> $hydrationMode     @see
     * @return Doctrine_Collection or Array
     */
    public function findWithLimit($dql, $params = array(), $limit = 10, $hydrationMode = null) {
        return $this->createQuery('u')
                ->where($dql, $params)
                ->orderBy('unit asc')
                ->limit($limit)
                ->execute();
    }

    /**
     * Find a unit, if not found create a new one
     * @param array $params array of $params[fieldname] = fieldvalue
     * @return Doctrine_Record Unit
     */
    public function findOrCreate($params) {

        $record;

        if (isset($params['unit'])) {
            $record = $this->findOneBy('unit', $params['unit']);
        }

        if (empty($record)) {
            $record = $this->create();
            $record->unit = $params['unit'];
            $record->save();
        }

        return $record;
    }
    
}